package com.example.demo.filter;

import com.example.demo.component.SpringHolder;
import com.example.demo.util.HostUtil;
import com.example.demo.util.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

public class ExecuteTimeFilter implements Filter {
    private Logger lg = LoggerFactory.getLogger(ExecuteTimeFilter.class);

    boolean enableVerification = false;

    private Set<String> publicServletUrl = new HashSet<>(1);
    public ExecuteTimeFilter(){
        publicServletUrl.add("/login");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // RequestContextListener or RequestContextFilter
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (publicServletUrl.contains(((HttpServletRequest)servletRequest).getServletPath())){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }



        if (enableVerification){
            if ("true".equals(SpringHolder.getCookieValue("l"))){
                print((HttpServletRequest) servletRequest);
                filterChain.doFilter(servletRequest, servletResponse);
            }else {
                servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
                String msg = "未登录";
                servletResponse.getWriter().print(msg);
            }
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    private void print(HttpServletRequest request) throws IOException {
        // 如果是GET请求就打印出GET请求的参数以及路径
        lg.info("请求路径：" + RequestUtil.getRequestParams(request));
        lg.info("请求的客户端信息：\tip=" + HostUtil.findRequestIp(request) + "，host=" + HostUtil.findRequestHost(request) + "，port=" + HostUtil.findRequestPort(request));

    }

    @Override
    public void destroy() {
        publicServletUrl.clear();
    }


}
